package com.example.autumn.web;

import com.example.autumn.context.AnnotationConfigApplicationContext;
import com.example.autumn.context.ApplicationContext;
import com.example.autumn.io.PropertyResolver;
import com.example.autumn.web.utils.WebUtils;
import jakarta.servlet.ServletContainerInitializer;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * @author liuzhiyong
 * @date 2023/11/10
 * description: 监听启动 初始刷IOC容器, 注册监听器, 创建DispatcherServlet, 注册DispatcherServlet
 */
public class ContextLoaderInitializer implements ServletContainerInitializer {

    final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 类似于SpringBoot的启动类
     */
    final Class<?> configClass;

    /**
     * 配置文件解析器
     */
    final PropertyResolver propertyResolver;

    public ContextLoaderInitializer(Class<?> configClass, PropertyResolver propertyResolver) {
        this.configClass = configClass;
        this.propertyResolver = propertyResolver;
    }

    @Override
    public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
        logger.info("Servlet container start. ServletContext = {}", ctx);
        // 获取编码 默认UTF-8
        String encoding = propertyResolver.getProperty("${autumn.web.character-encoding:UTF-8}");
        // 设置编码
        ctx.setRequestCharacterEncoding(encoding);
        ctx.setResponseCharacterEncoding(encoding);

        // 设置Servlet
        WebMvcConfiguration.setServletContext(ctx);

        // 创建IOC容器
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(this.configClass, this.propertyResolver);
        logger.info("Application context created: {}", applicationContext);

        // 注册过滤器
        WebUtils.registerFilters(ctx);

        // 注册 DispatcherServlet
        WebUtils.registerDispatcherServlet(ctx, this.propertyResolver);

    }
}
